package com.kuang.bascic.utils;

import com.kuang.org.domain.Employee;
import com.kuang.org.mapper.EmployeeMapper;
import com.kuang.user.domian.LoginInfo;
import com.kuang.user.domian.User;
import com.kuang.user.mapper.UserMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

public class LoginContext {

    /**
     * 这里工具类有两种类型 loginInfo里的type一种是管理员用户0 一种是普通用户1
     * @return
     * 传入登录信息  判断传入的是管理员还是用户
     * 静态方法泛型的方式<T>T
     */
    public static Object getCurrenUser(HttpServletRequest req){
        String header = req.getHeader("U-TOKEN");
        //2.去redis里面获取当前登录信息 logininfo
        // 静态方法无法调取spring容器里面的bean  通过原始方案获取spring容器在获取bean
        //ServletContext() 这是servlet四大作用域的application的类型 唯一的 跟随tomcat启动而启动 可以在任意req获取
        WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
        RedisTemplate redisTemplatel = context.getBean("redisTemplate", RedisTemplate.class);
        LoginInfo loginInfo = (LoginInfo) redisTemplatel.opsForValue().get(header);
        // 如果logininfo的type为0 就是管理员 从employee中获取id
        if (loginInfo.getType()==0){
            EmployeeMapper employeeMapper = context.getBean("employeeMapper", EmployeeMapper.class);
              Employee employee= employeeMapper.selectEmpByLoginId(loginInfo.getId());
              return employee;
        }
        //3.通过logininfo的id去user表的logininfo_id查询当前用户
        // 依然是用原方法获取spring容器 在获取bean
        UserMapper userMapper = context.getBean("userMapper", UserMapper.class);
        User user= userMapper.selectUserByLoginId(loginInfo.getId());
        return user;
    }
}
